#!/bin/bash

# ============================================
# Web3管理平台 - 一键安装脚本
# 支持 curl -fsSL url | bash 安装
# ============================================

set -e

readonly GREEN='\033[0;32m'
readonly BLUE='\033[0;34m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m'
readonly PROJECT_NAME="Web3管理平台"

echo -e "${BLUE}"
echo "╔════════════════════════════════════════════════════════╗"
echo "║              ${PROJECT_NAME} 一键安装                ║"
echo "║              curl | bash 零配置部署                   ║"
echo "╚════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# 配置项
INSTALL_DIR="./web3-management"
REPO_URL="https://gitee.com/0616_652/web3_management.git" # 替换为实际仓库
SERVICE_USER="web3"

# 检查权限并适配
check_permissions() {
    if [[ "$OS" == "macos" ]]; then
        echo "🍎 macOS开发模式部署"
        INSTALL_DIR="$(pwd)"  # 使用当前目录
        SERVICE_USER=$USER
        USE_SUDO=""  # macOS不需要sudo执行docker-compose

        echo "📁 安装目录: $INSTALL_DIR"
        echo "👤 运行用户: $SERVICE_USER"
        return
    fi

    if [[ $EUID -eq 0 ]]; then
        echo "🔧 检测到root用户，使用root模式部署"
        INSTALL_DIR="$(pwd)"  # 使用当前目录
        SERVICE_USER="root"
        USE_SUDO=""

        # root用户下的安全提示
        echo "⚠️  使用root部署的安全建议:"
        echo "   1. 确保服务器仅内网访问"
        echo "   2. 定期更新系统安全补丁"
        echo "   3. 配置防火墙规则"
        echo ""
        read -p "是否继续? (Y/n): " confirm
        if [[ $confirm =~ ^[Nn]$ ]]; then
            echo "❌ 用户取消部署"
            exit 0
        fi
        echo "✅ 确认继续，使用root模式部署"
    else
        echo "👤 检测到普通用户，使用安全模式部署"
        INSTALL_DIR="$(pwd)"  # 使用当前目录
        SERVICE_USER=$USER
        USE_SUDO="sudo"

        # 检查sudo权限
        if ! sudo -n true 2>/dev/null; then
            echo "🔐 需要sudo权限进行系统配置"
            sudo -v
        fi
    fi
}

# 检测系统
detect_system() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        VERSION=$(sw_vers -productVersion)
        echo "✅ 检测到系统: macOS $VERSION"
    elif [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS=$ID
        VERSION=$VERSION_ID
        echo "✅ 检测到系统: $OS $VERSION"
    else
        echo "❌ 无法检测操作系统"
        exit 1
    fi
}

# 安装依赖
install_dependencies() {
    echo "📦 检查系统依赖..."

    case $OS in
        macos)
            echo "🍎 检测到macOS系统..."

            # 检查Homebrew
            if ! command -v brew &> /dev/null; then
                echo "📦 安装Homebrew..."
                /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

                # 设置PATH
                if [[ -f "/opt/homebrew/bin/brew" ]]; then
                    export PATH="/opt/homebrew/bin:$PATH"
                elif [[ -f "/usr/local/bin/brew" ]]; then
                    export PATH="/usr/local/bin:$PATH"
                fi
            else
                echo "✅ Homebrew已存在"
            fi

            # 安装依赖
            echo "📦 安装必要工具..."

            # 检查Docker Desktop
            if ! command -v docker &> /dev/null; then
                echo "🐳 安装Docker Desktop..."
                echo "💡 正在下载Docker Desktop for Mac..."

                if [[ $(uname -m) == "arm64" ]]; then
                    # Apple Silicon Mac
                    curl -L "https://desktop.docker.com/mac/main/arm64/Docker.dmg" -o /tmp/Docker.dmg
                else
                    # Intel Mac
                    curl -L "https://desktop.docker.com/mac/main/amd64/Docker.dmg" -o /tmp/Docker.dmg
                fi

                echo "💡 请手动安装Docker Desktop:"
                echo "   1. 挂载镜像: hdiutil attach /tmp/Docker.dmg"
                echo "   2. 拖拽Docker到Applications文件夹"
                echo "   3. 启动Docker Desktop并等待完成"
                echo ""
                read -p "Docker Desktop安装完成后按Enter继续..."

                # 验证Docker安装
                if ! command -v docker &> /dev/null; then
                    echo "❌ Docker未正确安装，请检查"
                    exit 1
                fi
            else
                echo "✅ Docker已存在"
            fi

            # 检查Docker Compose (macOS Docker Desktop自带)
            if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
                echo "❌ Docker Compose未找到，请确保Docker Desktop正确安装"
                exit 1
            else
                echo "✅ Docker Compose已存在"
            fi
            ;;
        ubuntu|debian)
            $USE_SUDO apt-get update -qq
            $USE_SUDO apt-get install -y curl git docker.io docker-compose-plugin
            ;;
        centos|rhel|fedora)
            $USE_SUDO yum update -y -q
            $USE_SUDO yum install -y curl git docker docker-compose
            ;;
        slackware)
            echo "🔧 检测到Slackware系统 (可能是Unraid)..."

            # 检查Docker是否已安装
            if command -v docker &> /dev/null; then
                echo "✅ Docker已存在，跳过安装"
            else
                echo "❌ Docker未安装，请在Unraid管理界面启用Docker服务"
                echo "💡 启用步骤: Settings → Docker → Enable Docker: Yes"
                exit 1
            fi

            # 检查Docker Compose
            if ! command -v docker-compose &> /dev/null; then
                echo "📦 安装Docker Compose..."
                COMPOSE_VERSION="2.25.0"
                curl -L "https://mirrors.tuna.tsinghua.edu.cn/docker-compose/releases/v${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /tmp/docker-compose
                chmod +x /tmp/docker-compose
                mv /tmp/docker-compose /usr/local/bin/docker-compose
                echo "✅ Docker Compose安装完成"
            else
                echo "✅ Docker Compose已存在"
            fi

            # 检查git (Unraid通常需要手动安装)
            if ! command -v git &> /dev/null; then
                echo "📦 安装Git..."
                # Unraid使用nerdpack或手动安装
                echo "💡 正在尝试安装Git，如果失败请手动安装"
                wget -O /tmp/git.txz http://slackware.uk/slackware/slackware64-15.0/slackware64/d/git-2.37.1-x86_64-1.txz
                $USE_SUDO installpkg /tmp/git.txz 2>/dev/null || {
                    echo "⚠️  自动安装Git失败，请手动安装git后重试"
                    echo "   可在Unraid Community Applications中搜索Nerdpack安装git"
                    exit 1
                }
            else
                echo "✅ Git已存在"
            fi
            ;;
        arch)
            $USE_SUDO pacman -Sy --noconfirm curl git docker docker-compose
            ;;
        alpine)
            $USE_SUDO apk update
            $USE_SUDO apk add curl git docker docker-compose
            ;;
        *)
            echo "❌ 未识别的操作系统: $OS"
            echo "💡 检测到可能是Unraid或其他Docker预装系统"

            # 检查Docker是否可用
            if command -v docker &> /dev/null; then
                echo "✅ 检测到Docker已安装，继续部署..."

                # 安装Docker Compose (如果需要)
                if ! command -v docker-compose &> /dev/null; then
                    echo "📦 安装Docker Compose..."
                    COMPOSE_VERSION="2.21.0"
                    $USE_SUDO curl -L "https://github.com/docker/compose/releases/download/v${COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
                    $USE_SUDO chmod +x /usr/local/bin/docker-compose
                fi

                # 检查必需工具
                for tool in curl git; do
                    if ! command -v $tool &> /dev/null; then
                        echo "❌ 缺少必需工具: $tool"
                        echo "💡 请先安装 $tool 后重试"
                        exit 1
                    fi
                done
            else
                echo "❌ Docker未安装且无法自动安装"
                echo "💡 请先安装Docker和Docker Compose"
                exit 1
            fi
            ;;
    esac

    # 检查Docker服务状态
    if ! docker info &> /dev/null; then
        if [[ "$OS" == "macos" ]]; then
            echo "🔧 启动Docker Desktop..."
            echo "💡 请确保Docker Desktop已启动并运行"
            echo "   可以在Applications中找到Docker并启动"
            read -p "Docker Desktop启动后按Enter继续..."
        else
            echo "🔧 启动Docker服务..."
            $USE_SUDO systemctl start docker 2>/dev/null || {
                echo "💡 无法通过systemctl启动Docker，请确保Docker服务正在运行"
                echo "   Unraid用户: 请在Settings → Docker中启用Docker"
            }
            $USE_SUDO systemctl enable docker 2>/dev/null || true
        fi
    else
        echo "✅ Docker服务运行正常"
    fi

    # 配置Docker镜像加速 (针对国内网络)
    if [[ "$OS" != "macos" ]]; then
        echo "🔧 配置Docker镜像加速..."

        if [[ ! -f /etc/docker/daemon.json ]]; then
            # 创建新的配置文件
            mkdir -p /etc/docker
            tee /etc/docker/daemon.json > /dev/null << EOF
{
  "registry-mirrors": [
    "https://mirror.ccs.tencentyun.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com",
    "https://reg-mirror.qiniu.com"
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2"
}
EOF
            echo "✅ Docker镜像加速配置完成"
            DOCKER_CONFIG_CHANGED=true
        else
            echo "✅ Docker镜像加速已配置"
            DOCKER_CONFIG_CHANGED=false
        fi

        # 如果配置有变更，重启Docker
        if [[ "$DOCKER_CONFIG_CHANGED" == "true" ]]; then
            echo "🔄 重启Docker服务以应用配置..."
            systemctl restart docker 2>/dev/null || {
                echo "💡 请手动重启Docker服务"
            }
            sleep 5
        fi
    else
        echo "💡 macOS用户可在Docker Desktop设置中配置镜像加速"
    fi

    # 如果不是root，添加用户到docker组 (Linux only)
    if [[ $EUID -ne 0 && "$OS" != "macos" ]]; then
        $USE_SUDO usermod -aG docker $USER
        echo "💡 已将用户添加到docker组，重新登录后生效"
    fi

    echo "✅ 依赖检查完成"
}

# 创建服务用户
create_service_user() {
    # macOS和root用户跳过创建服务用户
    if [[ $EUID -eq 0 || "$OS" == "macos" ]]; then
        echo "👤 使用当前用户运行服务"
        return
    fi

    if ! id "$SERVICE_USER" &>/dev/null; then
        echo "👤 创建服务用户..."
        $USE_SUDO useradd -r -s /bin/bash -d $INSTALL_DIR $SERVICE_USER
        $USE_SUDO usermod -aG docker $SERVICE_USER
    fi
}

# 下载项目
download_project() {
    echo "📥 检查项目文件..."

    # 检查是否已在项目目录中
    if [[ -f "docker-compose.yml" && -f "backend/Dockerfile" ]]; then
        echo "✅ 检测到项目文件已存在，跳过下载"
        echo "📁 使用当前目录: $INSTALL_DIR"
        return
    fi

    echo "⚠️  当前目录不是Web3管理平台项目目录"
    echo "💡 请确保在项目根目录执行此脚本"
    echo "   或者自动下载项目文件"
    echo ""
    read -p "是否自动下载项目文件到当前目录? (Y/n): " download_confirm

    if [[ $download_confirm =~ ^[Nn]$ ]]; then
        echo "❌ 用户取消下载"
        exit 1
    fi

    # 清理当前目录并下载
    echo "🗑️  清理当前目录..."
    rm -rf docker-compose.yml backend frontend init.sql *.sh .env* 2>/dev/null || true

    # 下载项目文件
    echo "📥 下载项目文件到当前目录..."
    git clone --depth 1 --single-branch $REPO_URL /tmp/web3-temp
    cp -r /tmp/web3-temp/* .
    cp -r /tmp/web3-temp/.* . 2>/dev/null || true
    rm -rf /tmp/web3-temp

    echo "✅ 项目文件下载完成"
}

# 生成配置
generate_config() {
    echo "⚙️  生成配置文件..."

    # 生成简单密码
    MYSQL_ROOT_PASS="123456"
    MYSQL_USER_PASS="123456"
    JWT_SECRET=$(openssl rand -base64 64 | tr -d "=+/" | cut -c1-50)

    # macOS简化配置生成
    if [[ "$OS" == "macos" ]]; then
        tee $INSTALL_DIR/.env > /dev/null << EOF
# Web3管理平台 - macOS开发配置
MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASS
MYSQL_USER=web3user
MYSQL_PASSWORD=$MYSQL_USER_PASS
JWT_SECRET=$JWT_SECRET
JWT_EXPIRATION=86400
LOG_LEVEL=INFO
SHOW_SQL=false
TZ=Asia/Shanghai
EOF
        echo "✅ macOS配置生成完成"
        return
    fi

    # 根据用户权限生成配置
    if [[ $EUID -eq 0 ]]; then
        tee $INSTALL_DIR/.env > /dev/null << EOF
# Web3管理平台 - 自动生成配置 (Root模式)
MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASS
MYSQL_USER=web3user
MYSQL_PASSWORD=$MYSQL_USER_PASS
JWT_SECRET=$JWT_SECRET
JWT_EXPIRATION=86400
LOG_LEVEL=INFO
SHOW_SQL=false
TZ=Asia/Shanghai
EOF
    else
        $USE_SUDO -u $SERVICE_USER tee $INSTALL_DIR/.env > /dev/null << EOF
# Web3管理平台 - 自动生成配置 (安全模式)
MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASS
MYSQL_USER=web3user
MYSQL_PASSWORD=$MYSQL_USER_PASS
JWT_SECRET=$JWT_SECRET
JWT_EXPIRATION=86400
LOG_LEVEL=INFO
SHOW_SQL=false
TZ=Asia/Shanghai
EOF
    fi

    echo "✅ 配置生成完成"
}

# 安装系统服务
install_systemd_service() {
    echo "🔧 安装系统服务..."

    $USE_SUDO tee /etc/systemd/system/web3-management.service > /dev/null << EOF
[Unit]
Description=Web3管理平台
Requires=docker.service
After=docker.service

[Service]
Type=forking
User=$SERVICE_USER
WorkingDirectory=$INSTALL_DIR
ExecStart=/usr/bin/docker-compose up -d
ExecStop=/usr/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    $USE_SUDO systemctl daemon-reload
    $USE_SUDO systemctl enable web3-management

    echo "✅ 系统服务安装完成"
}

# 创建管理脚本
create_management_script() {
    echo "📝 创建管理脚本..."

    # 根据安装模式创建不同的管理脚本
    if [[ $EUID -eq 0 ]]; then
        # Root模式的管理脚本
        $USE_SUDO tee /usr/local/bin/web3-mgmt > /dev/null << EOF
#!/bin/bash
cd $INSTALL_DIR
case \${1:-status} in
    start)   systemctl start web3-management ;;
    stop)    systemctl stop web3-management ;;
    restart) systemctl restart web3-management ;;
    status)
        systemctl status web3-management --no-pager
        echo ""
        echo "访问地址: http://\$(hostname -I | awk '{print \$1}'):80"
        ;;
    logs)    docker-compose logs -f ;;
    update)
        git pull
        docker-compose build --quiet
        systemctl restart web3-management
        ;;
    dashboard) ./smart-deploy.sh --dashboard ;;
    *) echo "用法: \$0 {start|stop|restart|status|logs|update|dashboard}" ;;
esac
EOF
    else
        # 普通用户模式的管理脚本
        $USE_SUDO tee /usr/local/bin/web3-mgmt > /dev/null << EOF
#!/bin/bash
cd $INSTALL_DIR
case \${1:-status} in
    start)   sudo systemctl start web3-management ;;
    stop)    sudo systemctl stop web3-management ;;
    restart) sudo systemctl restart web3-management ;;
    status)
        sudo systemctl status web3-management --no-pager
        echo ""
        echo "访问地址: http://\$(hostname -I | awk '{print \$1}'):80"
        ;;
    logs)    docker-compose logs -f ;;
    update)
        sudo -u $SERVICE_USER git pull
        sudo -u $SERVICE_USER docker-compose build --quiet
        sudo systemctl restart web3-management
        ;;
    dashboard) sudo -u $SERVICE_USER ./smart-deploy.sh --dashboard ;;
    *) echo "用法: \$0 {start|stop|restart|status|logs|update|dashboard}" ;;
esac
EOF
    fi

    $USE_SUDO chmod +x /usr/local/bin/web3-mgmt
    echo "✅ 管理脚本创建完成 (使用 web3-mgmt 命令)"
}

# 部署完成信息
show_completion() {
    clear
    echo -e "${GREEN}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║                    🎉 部署完成！                         ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"

    echo "🌐 访问地址: http://$(hostname -I | awk '{print $1}'):80"
    echo "🔧 API地址:  http://$(hostname -I | awk '{print $1}'):8080"
    echo "👤 默认账号: admin / admin123"
    echo ""
    echo "🛠️  常用命令:"
    echo "  web3-mgmt status     # 查看状态"
    echo "  web3-mgmt logs       # 查看日志"
    echo "  web3-mgmt restart    # 重启服务"
    echo "  web3-mgmt dashboard  # 实时面板"
    echo "  web3-mgmt update     # 系统更新"
    echo ""
    echo "📁 安装路径: $INSTALL_DIR"
    echo "📋 日志位置: $INSTALL_DIR/logs/"
    echo ""
    echo "🔗 需要帮助? 运行: web3-mgmt dashboard"
}

# 主安装流程
main() {
    echo "开始一键安装..."
    echo ""

    echo "🔍 步骤1: 检查权限..."
    check_permissions  # 先检查权限
    echo "✅ 权限检查完成"

    echo "🔍 步骤2: 检测系统..."
    detect_system
    echo "✅ 系统检测完成"

    echo "🔍 步骤3: 安装依赖..."
    install_dependencies
    echo "✅ 依赖安装完成"

    echo "🔍 步骤4: 创建服务用户..."
    create_service_user
    echo "✅ 服务用户创建完成"

    echo "🔍 步骤5: 下载项目..."
    download_project
    echo "✅ 项目下载完成"

    echo "🔍 步骤6: 生成配置..."
    generate_config
    echo "✅ 配置生成完成"

    echo "🚀 启动服务..."
    cd $INSTALL_DIR

    # 预拉取镜像 (使用官方镜像+镜像加速)
    echo "📦 预拉取Docker镜像..."
    echo "💡 使用配置的镜像加速，请稍等..."

    # 预拉取基础镜像 (官方镜像，通过加速源拉取)
    docker pull mysql:8.0 || echo "⚠️  MySQL镜像拉取失败，将在启动时重试"
    docker pull redis:7-alpine || echo "⚠️  Redis镜像拉取失败，将在启动时重试"

    echo "✅ 基础镜像拉取完成"

    # 根据系统执行docker-compose
    echo "🔧 启动Docker Compose服务..."
    if [[ "$OS" == "macos" ]]; then
        # macOS直接启动
        docker-compose up -d
    elif [[ $EUID -eq 0 ]]; then
        # Linux root用户
        docker-compose up -d
    else
        # Linux普通用户
        $USE_SUDO -u $SERVICE_USER docker-compose up -d
    fi

    # 等待服务就绪
    echo "⏳ 等待服务启动..."
    sleep 15  # 减少等待时间

    # 快速健康检查
    echo -n "等待MySQL"
    for i in {1..15}; do
        if docker exec web3-mysql mysqladmin ping -h localhost -u root -p$MYSQL_ROOT_PASS &> /dev/null; then
            echo " ✅"
            break
        fi
        echo -n "."
        sleep 2
    done

    # 执行数据库迁移
    if [[ -f "backend/add_restart_fields.sql" ]]; then
        docker exec -i web3-mysql mysql -u root -p$MYSQL_ROOT_PASS web3_management < backend/add_restart_fields.sql 2>/dev/null || echo "⚠️  数据库迁移跳过"
    fi

    # macOS跳过systemd服务
    if [[ "$OS" != "macos" ]]; then
        install_systemd_service
        create_management_script
    else
        # macOS创建简化管理脚本
        tee /usr/local/bin/web3 > /dev/null << EOF
#!/bin/bash
cd $INSTALL_DIR
case \${1:-status} in
    start)   docker-compose up -d ;;
    stop)    docker-compose down ;;
    restart) docker-compose restart ;;
    status)
        docker-compose ps
        echo ""
        echo "访问地址: http://localhost:80"
        ;;
    logs)    docker-compose logs -f ;;
    update)
        git pull
        docker-compose up -d --build
        ;;
    *) echo "用法: \$0 {start|stop|restart|status|logs|update}" ;;
esac
EOF
        chmod +x /usr/local/bin/web3
        echo "✅ macOS管理脚本创建完成 (使用 'web3' 命令)"
    fi

    show_completion

    echo ""
    read -p "是否立即打开实时监控面板? (Y/n): " open_dashboard
    if [[ ! $open_dashboard =~ ^[Nn]$ ]]; then
        web3-mgmt dashboard
    fi
}

# 错误处理
trap 'echo -e "\n❌ 安装过程中出现错误"; exit 1' ERR

# 执行主流程
main "$@"
